package hn.cch.grammar.keyword;


public class SynchronizedDemo {


    public static void main(String[] args) {

        /**
         * object.wait() & object.notify() 都使用配合synchronized (object) {}使用
         */

        Object object = new Object(); // 锁：共享变量

        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                synchronized (object) {
                    try {
                        System.out.println(Thread.currentThread().getName() + ":wait begin");
                        object.wait(); // 等待
                        System.out.println(Thread.currentThread().getName() + ":wait end");
                    } catch (InterruptedException e) {
                        System.out.println(e.getMessage());
                    }
                }
                System.out.println(Thread.currentThread().getName() + ":stop");
            }, "thread-0-" + i).start();

            try {
                Thread.sleep(1);
                System.out.println(Thread.currentThread().getName() + "-" + i + ":sleep");
            } catch (InterruptedException e) {
                System.out.println(e.getMessage());
            }

            new Thread(() -> {
                synchronized (object) {
                    System.out.println(Thread.currentThread().getName() + ":notify begin");
                    object.notify(); // 唤醒
                    System.out.println(Thread.currentThread().getName() + ":notify end");
                }
                System.out.println(Thread.currentThread().getName() + ":stop");
            }, "thread-1-" + i).start();
        }

    }
}
